<?php
// set order-status 2 (processing)
define('MODULE_PAYMENT_QPAY_ORDER_STATUS_SUCCESS', 2);
// set order-status 99 (canceled)
define('MODULE_PAYMENT_QPAY_ORDER_STATUS_FAILED', 99);

function debug_msg($msg)
{
   $fh = fopen('qenta_notify_debug.txt', 'a');
   fwrite($fh, $msg."\n");
   //file_put_contents('qenta_notify_debug.txt', date().". ".$msg . "\n", FILE_APPEND);
   fclose($fh);

}
debug_msg('called script from '.$_SERVER['REMOTE_ADDR']);

if ($_POST) {

 include ('../../includes/application_top_callback.php');
 include ('../../includes/modules/payment/qpay.php');

 debug_msg("Finished Initialization of the qenta_notify.php script" );
 debug_msg("Received this POST: " . print_r($_POST, 1));
 $order_id = isset($_POST['order_id']) ? $_POST['order_id'] : 0;
 $q = xtc_db_query("INSERT INTO ".TABLE_PAYMENT_QPAY."
   (orders_id, qpay_response, created_at)
   VALUES
   ('$order_id','".serialize($_POST)."', NOW())");
 debug_msg('QPAY-Payment Table updated='.$q);
 if(isset($_POST['responseFingerprintOrder']) && isset($_POST['responseFingerprint'])) {
     $responseFingerprintOrder = explode(',', $_POST['responseFingerprintOrder']);
     $responseFingerprintSeed  = '';
     $c = 'QPAY'.strtoupper($_POST['initPaymentType']);
         foreach($responseFingerprintOrder as $k)
           $responseFingerprintSeed .= (strtoupper($k) == 'SECRET' ? qpay_core::constant("MODULE_PAYMENT_{$c}_PRESHARED_KEY") : $_POST[$k]);
         $calculated_fingerprint = md5($responseFingerprintSeed);
         if($calculated_fingerprint == $_POST['responseFingerprint']) {
             debug_msg('Fingerprint is OK');
             $order_status = ($_POST['paymentState'] == 'SUCCESS' ? MODULE_PAYMENT_QPAY_ORDER_STATUS_SUCCESS : MODULE_PAYMENT_QPAY_ORDER_STATUS_FAILED);
             debug_msg('Callback Process');
             $q = xtc_db_query('UPDATE ' . TABLE_ORDERS . ' SET orders_status=\'' . $order_status . '\' WHERE orders_id=\'' . $order_id.'\';');
             debug_msg('Order-Status updated='.$q);
             $avsStatusCode = isset($_POST['avsResponseCode']) ? $_POST['avsResponseCode'] : '';
             $avsStatusMessage = isset($_POST['avsResponseMessage']) ? $_POST['avsResponseMessage'] : '';
             if($avsStatusCode != '' && $avsStatusMessage != '')
             {
                 $avsStatus = 'AVS Result: ' . $avsStatusCode . ' - ' . $avsStatusMessage;
             }
             else
             {
                 $avsStatus = '';
             }
             debug_msg($avsStatus);
             $q = xtc_db_query("INSERT INTO ".TABLE_ORDERS_STATUS_HISTORY."
             (orders_id,  orders_status_id, date_added, customer_notified, comments)
             VALUES
               ('$order_id', '$order_status', NOW(), '0', '$avsStatus')");
             debug_msg('Order-Status-History updated='.$q);
         }
         else
         {
             debug_msg('Invalid Responsefingerprint.');
             debug_msg('calc-fingerprint: ' .$calculated_fingerprint);
             debug_msg('response-fingerprint: '. $_POST['responseFingerprint']);
         }
     } else {
         debug_msg('Fingerprint is Not OK');
         if(isset($_POST['paymentState']) && $_POST['paymentState'] == 'CANCEL') {
             debug_msg('Order is Canceled');
             $order_status = MODULE_PAYMENT_QPAY_ORDER_STATUS_FAILED;

             debug_msg('Callback Process');
             $q = xtc_db_query("UPDATE ".TABLE_ORDERS."
               SET orders_status='$order_status',
                 gm_cancel_date='".date('Y-m-d H:i:s')."'
               WHERE orders_id='$order_id'");
             debug_msg('Order-Status updated='.$q);
             $q = xtc_db_query("INSERT INTO ".TABLE_ORDERS_STATUS_HISTORY."
               (orders_id,  orders_status_id, date_added, customer_notified, comments)
               VALUES
               ('$order_id', '$order_status', NOW(), '0', '')");
             debug_msg('Order-Status-History updated='.$q);
             // restock order
             xtc_remove_order($order_id, $restock = true);
             debug_msg('Order Restocked');
         } elseif(isset($_POST['paymentState']) && $_POST['paymentState'] == 'FAILURE') {
             $message = isset($_POST['message']) ? htmlentities($_POST['message']) : '';
             debug_msg('Order Failed: '.$message);
             $order_status = MODULE_PAYMENT_QPAY_ORDER_STATUS_FAILED;
           debug_msg('Callback Process');
             $q = xtc_db_query("UPDATE ".TABLE_ORDERS."
               SET orders_status='$order_status',
                 gm_cancel_date='".date('Y-m-d H:i:s')."'
               WHERE orders_id='$order_id'");
             debug_msg('Order-Status updated='.$q);
             $q = xtc_db_query("INSERT INTO ".TABLE_ORDERS_STATUS_HISTORY."
               (orders_id,  orders_status_id, date_added, customer_notified, comments)
               VALUES
               ('$order_id', '$order_status', NOW(), '0', '$message')");
             debug_msg('Order-Status-History updated='.$q);
             // restock order
             xtc_remove_order($order_id, $restock = true);
             debug_msg('Order Restocked');
         }
     }
}

header("HTTP/1.0 200 OK");
debug_msg("-- script reached eof - executed without errors --\n");

// from admin/includes/functions/general.php
function xtc_remove_order($order_id, $restock = false)
{
    if ($restock == 'on')
    {
        // BOF GM_MOD:
        $order_query = xtc_db_query("
                                    SELECT
                                        op.orders_products_id,
                                        op.products_id,
                                        op.products_quantity,
                                        o.date_purchased
                                    FROM " .
                                        TABLE_ORDERS_PRODUCTS . " op
                                    LEFT JOIN  " .
                                        TABLE_ORDERS . " o
                                    ON
                                        op.orders_id = o.orders_id
                                    WHERE
                                        op.orders_id = '" . xtc_db_input($order_id) . "'
        ");

        while ($order = xtc_db_fetch_array($order_query))
        {
            /* BOF SPECIALS RESTOCK */
            $t_query = xtc_db_query("
                                    SELECT
                                        specials_date_added
                                    AS
                                        date
                                    FROM " .
                                        TABLE_SPECIALS . "
                                    WHERE
                                        specials_date_added < '" .  $order['date_purchased']    . "'
                                    AND
                                        products_id         = '" .  $order['products_id']       . "'
            ");

            if((int)xtc_db_num_rows($t_query) > 0)
            {
                xtc_db_query("
                                UPDATE " .
                                    TABLE_SPECIALS . "
                                SET
                                    specials_quantity = specials_quantity + " . $order['products_quantity'] . ",
                                    status = 1
                                WHERE
                                    products_id = '" . $order['products_id'] . "'
                ");
            }
            /* EOF SPECIALS RESTOCK */

            xtc_db_query("
                            UPDATE " .
                                TABLE_PRODUCTS . "
                            SET
                                products_quantity = products_quantity + ".$order['products_quantity'].",
                                products_ordered = products_ordered - ".$order['products_quantity'].",
                                products_status = 1
                            WHERE
                                products_id = '".$order['products_id']."'
            ");

            // BOF GM_MOD
            if(ATTRIBUTE_STOCK_CHECK == 'true')
            {
                $gm_get_orders_attributes = xtc_db_query("
                                                        SELECT
                                                            products_options,
                                                            products_options_values
                                                        FROM
                                                            orders_products_attributes
                                                        WHERE
                                                            orders_id = '" . xtc_db_input($order_id) . "'
                                                        AND
                                                            orders_products_id = '" . $order['orders_products_id'] . "'
                ");

                while($gm_orders_attributes = xtc_db_fetch_array($gm_get_orders_attributes))
                {
                    $gm_get_attributes_id = xtc_db_query("
                                                        SELECT
                                                            pa.products_attributes_id
                                                        FROM
                                                            products_options_values pov,
                                                            products_options po,
                                                            products_attributes pa
                                                        WHERE
                                                            po.products_options_name = '" . $gm_orders_attributes['products_options'] . "'
                                                            AND po.products_options_id = pa.options_id
                                                            AND pov.products_options_values_id = pa.options_values_id
                                                            AND pov.products_options_values_name = '" . $gm_orders_attributes['products_options_values'] . "'
                                                            AND pa.products_id = '" . $order['products_id'] . "'
                                                        LIMIT 1
                    ");

                    if(xtc_db_num_rows($gm_get_attributes_id) == 1)
                    {
                        $gm_attributes_id = xtc_db_fetch_array($gm_get_attributes_id);

                        xtc_db_query("
                                        UPDATE
                                            products_attributes
                                        SET
                                            attributes_stock = attributes_stock + ".$order['products_quantity']."
                                        WHERE
                                            products_attributes_id = '" . $gm_attributes_id['products_attributes_id'] . "'
                        ");
                    }
                }
            }
            // EOF GM_MOD
        }
    }
}
?>
